﻿using System;
using System.Collections.Generic;

namespace Framework
{

    public class ReferenceCollection
    {
        private Type m_ReferenceType;
        public Type ReferenceType => m_ReferenceType;
        private Queue<IReference> m_References;
        public  T Acquire<T>() where T : class, IReference, new()
        {
            if (typeof(T) != m_ReferenceType)
            {
                throw new GameFrameworkException("Type is invalid.");
            }
            lock (m_References)
            {
                if (m_References.Count > 0)
                {
                    return (T)m_References.Dequeue();
                }
            }
            return new T();
        }

        /// <summary>
        /// 将引用归还引用池。
        /// </summary>
        /// <param name="reference">引用。</param>
        public  void Release(IReference reference)
        {
            reference.Clear();
            lock (m_References)
            {
                if (m_References.Contains(reference))
                {
                    throw new GameFrameworkException("The reference has been released.");
                }

                m_References.Enqueue(reference);
            }
        }

        public ReferenceCollection(Type referenceType)
        {
            m_ReferenceType = referenceType;
            m_References = new Queue<IReference>();
        }
    }

}